import ErrorHandler from './ErrorHandler';
import aes from 'crypto-js/aes';
import CryptoJS from 'crypto-js';
import md5 from 'crypto-js/md5';
import isEmpty from 'lodash/isEmpty';
import AsyncStorage from '@react-native-community/async-storage';

const apiKey = 'VVuucskey201906';
const secret = 'VVuucs_sec201906';
const getDecrypt = (params, secrets) =>
  JSON.parse(
    aes
      .decrypt(params, CryptoJS.enc.Utf8.parse(secrets), {
        iv: CryptoJS.enc.Utf8.parse(secrets),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
      })
      .toString(CryptoJS.enc.Utf8)
  );

const utils = {
  getSign: (timeStamp, apiKeys, params) =>
    md5(`${timeStamp}${apiKeys}${params}`).toString().toUpperCase(),
  encrypt: (data, secrets) =>
    aes
      .encrypt(JSON.stringify(data), CryptoJS.enc.Utf8.parse(secrets), {
        iv: CryptoJS.enc.Utf8.parse(secrets),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
      })
      .toString(),
  decrypt: (params, secrets, encryption = true) => {
    // encryption === false 不去解密响应报文
    if (typeof params !== 'string' || encryption === false) {
      return params;
    }
    try {
      return params && !isEmpty(params) ? getDecrypt(params, secrets) : params;
    } catch (e) {
      console.error(e);
      return params;
    }
  },
};

export default function inject(request, location) {
  request.interceptors.request.use(
    async (options) => {
      // console.log('请求参数', options);
      const now = +new Date();
      const { data = {} } = options;
      const params = utils.encrypt(data, secret);
      const userDataString = await AsyncStorage.getItem('user');
      const newUser = userDataString ? JSON.parse(userDataString) : {};
      if (!['GET', 'get'].includes(options.method)) {
        options.data = {
          params,
          sign: utils.getSign(now, apiKey, params),
          timeStamp: now,
        };
      }
      options.headers = {
        Authorization: (await AsyncStorage.getItem('Authorization')) || '',
        uc: newUser.userCode || '',
      };
      return options;
    },
    (error) => {
      // Toast.info('请求错误 ==>' + error.message);
      return Promise.reject(error);
    }
  );

  request.interceptors.response.use(
    (result) => {
      if (
        result.data &&
        result.data.response &&
        result.data.response.status !== 200
      ) {
        throw new Error(result.data);
      }
      return Promise.resolve({
        ...result.data,
        code: result.data.code,
        data: {
          ...utils.decrypt(result.data.data, secret, true),
        },
      });
    },
    (error) => {
      // Toast.info('返回错误 ==>' + error.message);
      ErrorHandler.handleHttpError({ ...error });
      return Promise.reject(error);
    }
  );
}
